package com.emellend.api11.preference;

import com.emellend.api11.R;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

public class LaunchingPreferences extends Activity implements OnClickListener {
	private static final int REQUEST_CODE_PREFERENCES=1;
	private TextView counterText;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		PreferenceManager.setDefaultValues(this, R.xml.advanced_preferences, false);
		
		LinearLayout layout=new LinearLayout(this);
		layout.setOrientation(LinearLayout.VERTICAL);
		setContentView(layout);
		
		Button launchPreferences=new Button(this);
		launchPreferences.setText(getString(R.string.launch_preference_activity));
		launchPreferences.setOnClickListener(this);
		layout.addView(launchPreferences,
				new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
		
		counterText=new TextView(this);
		layout.addView(counterText,
				new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
		
		updateCounterText();
	}
	@Override
	public void onClick(View v) {
		Intent launchPreferencesIntent=new Intent(this, AdvancedPreferences.class);
		startActivityForResult(launchPreferencesIntent, REQUEST_CODE_PREFERENCES);
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode==REQUEST_CODE_PREFERENCES) {
			updateCounterText();
		}
	}
	
	private void updateCounterText() {
		SharedPreferences sharedPref=PreferenceManager.getDefaultSharedPreferences(this);
		final int counter=sharedPref.getInt(AdvancedPreferences.KEY_MY_PREFERENCE, 0);
		counterText.setText(getString(R.string.counter_value_is)+" "+counter);
	}
}
